package com.test.daily.leetcode.y2022.m06.day0629.home.v02;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Tom on 2022/6/29
 */
public class Solution {
    public class Codec {
        public Map<String, String> origin2Short = new HashMap<>(), short2Origin = new HashMap<>();
        String str1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String url = "http://abc.com/";
        public Random random = new Random();
        public int k = 6;

        public String encode(String longUrl) {
            int length = str1.length();
            while (!origin2Short.containsKey(longUrl)) {
                char[] cs = new char[k];
                for (int i = 0; i < k; i++) {
                    cs[i] = str1.charAt(random.nextInt(length));
                }
                String cur = url + String.valueOf(cs);
                if (short2Origin.containsKey(cur)) {
                    continue;
                }
                origin2Short.put(longUrl, cur);
                short2Origin.put(cur, longUrl);
            }
            return origin2Short.get(longUrl);
        }

        public String decode(String shortUrl) {
            return short2Origin.get(shortUrl);
        }
    }
}
